package com.sen.gateway.auth;

import com.sen.common.common.response.MessageResult;
import com.sen.common.common.response.ResultMsgEnum;
import com.sen.common.common.util.JacksonUtils;
import com.sen.gateway.util.WebfluxResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 401未授权异常处理，转换为JSON
 * @author esjiang
 */
@Slf4j
public class JsonAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
        if (e instanceof OAuth2AuthenticationException){
            OAuth2Error error = ((OAuth2AuthenticationException) e).getError();
            log.error(this.getClass().getName() + JacksonUtils.toJSONString(error),error);
            return WebfluxResponseUtils.responseWrite(exchange, error);
        }
        return WebfluxResponseUtils.responseWrite(exchange, MessageResult.reqFailed(ResultMsgEnum.UNAUTHORIZED));
    }
}
